/**
 * Send a batch of AJAX requests to the server.
 *
 * Accepts as argument a list of objects, each object should be in the
 * following structure:
 *
 * {
 *     data:{
 *         controller:(The name of the controller to call),
 *         method:(The name of the method to call),
 *         params:(An object with the AJAX request's params)
 *     },
 *     success:(a function to call upon success with the results)
 * }
 */
function makeMultipleAjaxRequests(args,error){
	var data=[];
	var successFunctions=[];
	if(!(args instanceof Array))
		args=[args];
	for(i in args){
		data.push(args[i].data);
		if(args[i].success instanceof Function)
			successFunctions.push(args[i].success);
		else
			successFunctions.push(function(){});
	}
	if(!error){
		error=function(jqXHR,textStatus,errorThrown){
			alert(errorThrown);
		}
	}
	$.ajax({
			url:'ajax',
			type:'POST',
			data:JSON.stringify({
					userId:facebookUserId,
					request:data
			}),
			contentType:"application/json;charset=utf-8",
			dataType:'json',
			success:function(resultData,textStatus,jqXHR){
				if('errors' in resultData){
					var errorMessage="";
					for(var i in resultData.errors){
						errorMessage+=resultData.errors[i].error+"\n";
						for(var j in resultData.errors[i].stackTrace){
							errorMessage+=resultData.errors[i].stackTrace[j]+"\n";
						}
					}
					error(jqXHR,textStatus,errorMessage);
				}else{
					for(i in resultData){
						var singleResult=resultData[i];
						if('string'===typeof(singleResult))
							error(jqXHR,textStatus,singleResult);
						else
							successFunctions[i](resultData[i]);
					}
				}
			},
			error:error
	});
}

/**
 * Make a single AJAX request.
 */
function ajaxRequest(controller,method,params,success,error){
	makeMultipleAjaxRequests({
			data:{
				controller:controller,
				method:method,
				params:params
			},
			success:success,
	},error);
}
